package ru.timofeyco.justfeelbetter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import ru.timofeyco.justfeelbetter.adapters.MonthAdapter;
import ru.timofeyco.justfeelbetter.db.JustFeelBetterDatabase;
import ru.timofeyco.justfeelbetter.model.DayDrills;
import ru.timofeyco.justfeelbetter.model.DayResult;
import ru.timofeyco.justfeelbetter.model.Drill;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Display;
import android.widget.GridView;
import android.widget.TextView;

public class MonthActivity extends Activity {
	JustFeelBetterDatabase dbHelper;
	GridView gridView;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHelper = new JustFeelBetterDatabase(this);
        
        setContentView(R.layout.month);
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM yyyy");
        TextView textView = (TextView)findViewById(R.id.monthCaptionTextView);
        textView.setText(dateFormat.format(Calendar.getInstance().getTime()));

        this.gridView = (GridView)findViewById(R.id.monthGridView);
        updateMonthView();
    }
	
	private void updateMonthView() {
		updateDayResultView();
		
		Display display = getWindowManager().getDefaultDisplay();
        new Rect(0, 0, display.getWidth(), display.getHeight());
        
		int countDays = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
        DayResult[] monthResult = initializeMonthResult(countDays);
        
        gridView.setAdapter(new MonthAdapter(this, 5, countDays / 5, monthResult));
        gridView.setNumColumns(5);
        gridView.setVerticalSpacing(5);
        gridView.setHorizontalSpacing(5);
        gridView.setColumnWidth(display.getWidth() / 5);
        gridView.setEnabled(false);
	}
	
	private void updateDayResultView() {
    	DayDrills dayDrills = new DayDrills();
        Date currDate = Calendar.getInstance().getTime();
        Date currDay = new Date(currDate.getYear(), currDate.getMonth(), currDate.getDate());
        dayDrills.setDate(currDay);
        
        Drill[] drills = dbHelper.getDayDrills(currDay);        
        int productivityPercent = DayResultView.calculatePercent(new ArrayList<Drill>(Arrays.asList(drills)));        
        
        dbHelper.updateDayResult(new DayResult(currDay, productivityPercent));
    }

	private DayResult[] initializeMonthResult(int countDays) {
		return dbHelper.getMonthResult(Calendar.getInstance().getTime(), countDays);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		updateMonthView();
	}
	
	
}
